﻿using System;
using System.Web;
using System.Windows.Forms;
using GC_VKMD.MusicDownloader.Constants.Vkontakte;
using GC_VKMD.MusicDownloaderClient.Abstractions.Interfaces.Helpers;
using GC_VKMD.MusicDownloaderClient.Enums;
using GC_VKMD.MusicDownloaderClient.Helpers;
using UserControl = System.Windows.Controls.UserControl;

namespace GC_VKMD.MusicDownloaderClient.UserControls
{
	/// <summary>
	/// Interaction logic for WinFormsWebBrowser.xaml
	/// </summary>
	public partial class VKAutorization : UserControl
	{
		#region Constants

		private const string URL_PARAMETER_ACCESS_TOKEN = "access_token";
		private const string URL_PARAMETER_USER_ID = "user_id";

		#endregion

		#region Variables

		private readonly IApplicationConfiguration _applicationConfiguration;

		#endregion

		#region Constructors

		public VKAutorization()
		{
			InitializeComponent();

			var uri = new Uri(GetType().Assembly.GetName().CodeBase);
			_applicationConfiguration = new ApplicationConfiguration(uri.LocalPath);

			InitWebBrowser();
		}

		#endregion

		#region Event Handlers

		private void WbVkAutorizeOnNavigated(object sender, WebBrowserNavigatedEventArgs e)
		{
			if (e.Url == null || string.IsNullOrWhiteSpace(e.Url.Fragment)) return;

			var urlParams = HttpUtility.ParseQueryString(e.Url.Fragment.Substring(1));

			_applicationConfiguration.Token = urlParams.Get(URL_PARAMETER_ACCESS_TOKEN);
			_applicationConfiguration.UserId = urlParams.Get(URL_PARAMETER_USER_ID);
		}

		#endregion

		#region Internal Implamentation

		private void InitWebBrowser()
		{
			wbVKAutorize.Navigated += WbVkAutorizeOnNavigated;

			wbVKAutorize.Navigate(String.Format(VKUrlTemplate.Autorize, _applicationConfiguration.AppId, VKScope.Audio));
		}

		#endregion
	}
}
